﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using chihuopig.Tool;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using chihuopig.Model;
using System.Text;
using SqlSugar;
using chihuopig.Web.verfiy;
using System.Text.RegularExpressions;

namespace chihuopig.Web.Framework
{
    public class AdminWattantyController: WebViewController
    {

        IHttpContextAccessor _IHttpContextAccessor;
        public AdminWattantyController(IHttpContextAccessor iHttpContextAccessor)
        {
            _IHttpContextAccessor = iHttpContextAccessor;
        }
        protected chihuopig.Model.Admin admin
        {
            get
            {
                var id = UtilityHelper.GetCookieValue(CookieKeysCollection.Buffalo_Admin, CookieKeysCollection.Buffalo_Admin_Key);
                if (string.IsNullOrWhiteSpace(id))
                {
                    return null;
                }
                return chihuopig.Service.DBService.Sqlclient.Queryable<chihuopig.Model.Admin>().Where(s => s.Id.ToString() == id&&s.IsDelete==false).Single();
            }
        }

        

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (admin==null)
            {
                context.Result = new RedirectResult("/admin/Login/LoginIndex");
            }
            else
            {
               string path=Regex.Match(context.HttpContext.Request.Path.Value, "^/[a-zA-Z]+/[a-zA-Z]+/[a-zA-Z]+").Value;
               //System.Attribute[] atts = System.Attribute.GetCustomAttributes(context.ActionDescriptor.GetType());
               // AdminMenuFilterAttribute sas = atts[0] as AdminMenuFilterAttribute;
               // System.Attribute[] atts2 = System.Attribute.GetCustomAttributes(typeof(ActionResult));
               // object[] ss = context.ActionDescriptor.GetType().GetCustomAttributes(typeof(ActionResult), false);

                List<string> PrerogativeList= chihuopig.Service.DBService
                    .Sqlclient
                    .Queryable<chihuopig.Model.jurisdiction, chihuopig.Model.Role_Jurisdiction, chihuopig.Model.AdminRole>
                    ((j, r, a) => new object[]
                    {
                        JoinType.Left,r.JurisdictionId==j.Id,
                        JoinType.Left,a.RoleId==r.RoleId
                    })
                    .Where((j, r, a) => a.AdminId == admin.Id&&j.Page== path)
                    .Select((j, r, a) =>j.Prerogative)
                    .ToList();
                
                if(PrerogativeList.Count<=0)
                {
                    ContentResult res = new ContentResult();
                    res.Content = "没有权限";
                    context.Result = res;
                }
               
                
            }
        }
    }
}
